import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({
  selector: 'simple-http',
  template: `
    <h2>Basic Request</h2>
    <button type="button" (click)="makeRequest()">提出请求</button>
    <div *ngIf="loading">loading...</div>
    <pre>{{data | json}}</pre>
  `})
export class SimpleHttpComponent{

  data: object;
  loading: boolean;

  constructor(private http: Http){
  }

  /**
   * 提出请求
   * http://jsonplaceholder.typicode.com/posts/1
  */
  makeRequest(): void {
    this.loading = true;
    this.http.request('http://jsonplaceholder.typicode.com/posts/1')
      .subscribe(
        (res: Response) => { // 当 http.request （从服务器）返回一个流时，它就会发出一个 Response 对象。我们用 json方法提取出响应体并解析成一个 Object ，然后将这个 Object 赋值给 this.data 。
        this.data = res.json();
        this.loading = false;},
      );
  }
}
